package com.sheliduan.itlearning.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sheliduan.itlearning.admin.service.AdminCourseService;
import com.sheliduan.itlearning.admin.model.vos.course.DeleteCourseReqVO;
import com.sheliduan.itlearning.blogger.model.vos.course.FindCourseDetailsRspVO;
import com.sheliduan.itlearning.blogger.model.vos.course.FindCoursePageListReqVO;
import com.sheliduan.itlearning.blogger.model.vos.course.FindCoursePageListRspVO;
import com.sheliduan.itlearning.blogger.model.vos.course.UpdateCourseReqVO;
import com.sheliduan.itlearning.common.domain.dos.*;
import com.sheliduan.itlearning.common.domain.mapper.*;
import com.sheliduan.itlearning.common.model.vos.IdTypeReqVO;
import com.sheliduan.itlearning.common.utils.PageResponseData;
import com.sheliduan.itlearning.common.utils.ResponseData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 断舍离
 * @date: 2025/3/20 15:01
 * @description: 后台管理员课程Service实现类
 **/
@Service
public class AdminCourseServiceImpl implements AdminCourseService {

    @Autowired
    private ArticleCourseMapper articleCourseMapper;

    @Autowired
    private VideoCourseMapper videoCourseMapper;

    @Autowired
    private ArticleCategoryRelMapper articleCategoryRelMapper;

    @Autowired
    private ArticleTagRelMapper articleTagRelMapper;

    @Autowired
    private VideoCategoryRelMapper videoCategoryRelMapper;

    @Autowired
    private VideoTagRelMapper videoTagRelMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private TagMapper tagMapper;

    @Override
    public PageResponseData findArticleCoursePageList(FindCoursePageListReqVO reqVO) {
        long current = reqVO.getCurrent();
        long size = reqVO.getSize();
        String title = reqVO.getTitle();
        LocalDateTime startDate = reqVO.getStartDate();
        LocalDateTime endDate = reqVO.getEndDate();
        Page<ArticleCourseDO> page = articleCourseMapper.selectPageListByAdmin(current, size, title, startDate, endDate);
        List<ArticleCourseDO> articleCourseDOS = page.getRecords();
        List<FindCoursePageListRspVO> vos = new ArrayList<>();
        // 若查询分页数据不为空, 则采用流操作封装vo集合
        if(!CollectionUtils.isEmpty(articleCourseDOS)){

            vos = articleCourseDOS.stream()
                    .map(articleCourseDO -> FindCoursePageListRspVO.builder()
                            .id(articleCourseDO.getId())
                            .title(articleCourseDO.getTitle())
                            .cover(articleCourseDO.getCover())
                            .summary(articleCourseDO.getSummary())
                            .price(articleCourseDO.getPrice())
                            .username(userMapper.selectById(articleCourseDO.getUserId()).getUsername())
                            .contentOrLocation(articleCourseDO.getContent())
                            .status(articleCourseDO.getStatus())
                            .type(articleCourseDO.getType())
                            .build())
                    .collect(Collectors.toList());

        }
        return PageResponseData.success(page, vos);
    }

    @Override
    public PageResponseData findVideoCoursePageList(FindCoursePageListReqVO reqVO) {
        long current = reqVO.getCurrent();
        long size = reqVO.getSize();
        String title = reqVO.getTitle();
        LocalDateTime startDate = reqVO.getStartDate();
        LocalDateTime endDate = reqVO.getEndDate();
        Page<VideoCourseDO> page = videoCourseMapper.selectPageListByAdmin(current, size, title, startDate, endDate);
        List<VideoCourseDO> videoCourseDOS = page.getRecords();
        List<FindCoursePageListRspVO> vos = new ArrayList<>();
        // 若查询分页数据不为空, 则采用流操作封装vo集合
        if(!CollectionUtils.isEmpty(videoCourseDOS)){

            vos = videoCourseDOS.stream()
                    .map(videoCourseDO -> FindCoursePageListRspVO.builder()
                            .id(videoCourseDO.getId())
                            .title(videoCourseDO.getTitle())
                            .cover(videoCourseDO.getCover())
                            .summary(videoCourseDO.getSummary())
                            .price(videoCourseDO.getPrice())
                            .username(userMapper.selectById(videoCourseDO.getUserId()).getUsername())
                            .contentOrLocation(videoCourseDO.getLocation())
                            .status(videoCourseDO.getStatus())
                            .type(videoCourseDO.getType())
                            .build())
                    .collect(Collectors.toList());
        }
        return PageResponseData.success(page, vos);
    }

    @Override
    @Transactional
    public ResponseData deleteCourse(DeleteCourseReqVO reqVO) {
        // 根据课程类型, 删除对应的课程即课程_分类/课程_标签关联信息
        if (reqVO.getType() == 0) {
            articleCourseMapper.deleteById(reqVO.getId());
            articleCategoryRelMapper.deleteRelByArticleId(reqVO.getId());
            articleTagRelMapper.deleteRelByArticleId(reqVO.getId());
            updateTotal(reqVO.getStatus(), reqVO.getType(), reqVO.getId());
        } else {
            videoCourseMapper.deleteById(reqVO.getId());
            videoCategoryRelMapper.deleteRelByVideoId(reqVO.getId());
            videoTagRelMapper.deleteRelByVideoId(reqVO.getId());
            updateTotal(reqVO.getStatus(), reqVO.getType(), reqVO.getId());
        }
        return ResponseData.success();
    }

    /*
     * 更新对应分类、标签下的文章/视频课程总数
     * */
    private void updateTotal(Integer status, Integer type, Integer id) {
        if(type == 0 && status == 2) {
            // 更新对应分类、标签下的文章课程总数
            LambdaQueryWrapper<ArticleCategoryRelDO> wrapperCategory = Wrappers.lambdaQuery();
            wrapperCategory.eq(ArticleCategoryRelDO::getArticleId, id);
            // 该文章对应的分类
            CategoryDO categoryDO = categoryMapper.selectById(articleCategoryRelMapper.selectOne(wrapperCategory).getCategoryId());
            LambdaQueryWrapper<ArticleTagRelDO> wrapperTag = Wrappers.lambdaQuery();
            wrapperTag.eq(ArticleTagRelDO::getArticleId, id);
            // 该文章对应的标签
            TagDO tagDO = tagMapper.selectById(articleTagRelMapper.selectOne(wrapperTag).getTagId());
            categoryDO.setArticleTotal(categoryDO.getArticleTotal() - 1);
            categoryMapper.updateById(categoryDO);
            tagDO.setArticleTotal(tagDO.getArticleTotal() - 1);
        }else if(type == 1 && status == 2){
            // 更新对应分类、标签下的视频课程总数
            LambdaQueryWrapper<VideoCategoryRelDO> wrapperCategory = Wrappers.lambdaQuery();
            wrapperCategory.eq(VideoCategoryRelDO::getVideoId, id);
            // 该视频对应的分类
            CategoryDO categoryDO = categoryMapper.selectById(videoCategoryRelMapper.selectOne(wrapperCategory).getCategoryId());
            LambdaQueryWrapper<VideoTagRelDO> wrapperTag = Wrappers.lambdaQuery();
            wrapperTag.eq(VideoTagRelDO::getVideoId, id);
            // 该视频对应的标签
            TagDO tagDO = tagMapper.selectById(videoTagRelMapper.selectOne(wrapperTag).getTagId());
            categoryDO.setArticleTotal(categoryDO.getArticleTotal() - 1);
            categoryMapper.updateById(categoryDO);
            tagDO.setArticleTotal(tagDO.getArticleTotal() - 1);
            tagMapper.updateById(tagDO);
        }
    }

    @Override
    @Transactional
    public ResponseData updateArticleCourse(UpdateCourseReqVO reqVO) {
        // 封装修改文章课程实体类
        ArticleCourseDO articleCourseDO = ArticleCourseDO.builder()
                .id(reqVO.getId())
                .title(reqVO.getTitle())
                .cover(reqVO.getCover())
                .summary(reqVO.getSummary())
                .content(reqVO.getContentOrLocation())
                .price(reqVO.getPrice())
                .status(reqVO.getStatus())
                .updateTime(new Date())
                .build();
        // 修改文章课程
        articleCourseMapper.updateCourse(articleCourseDO);

        // 修改文章课程_分类关联
        articleCategoryRelMapper.updateRelByArticleId(reqVO.getId(), reqVO.getCategoryId());

        // 修改文章课程_标签关联
        articleTagRelMapper.updateRelByArticleId(reqVO.getId(), reqVO.getTagId());
        return ResponseData.success();
    }

    @Override
    @Transactional
    public ResponseData updateVideoCourse(UpdateCourseReqVO reqVO) {
        // 封装修改视频课程实体类
        VideoCourseDO videoCourseDO = VideoCourseDO.builder()
                .id(reqVO.getId())
                .title(reqVO.getTitle())
                .cover(reqVO.getCover())
                .summary(reqVO.getSummary())
                .location(reqVO.getContentOrLocation())
                .price(reqVO.getPrice())
                .status(reqVO.getStatus())
                .updateTime(new Date())
                .build();
        // 修改视频课程
        videoCourseMapper.updateCourse(videoCourseDO);

        // 修改视频课程_分类关联
        videoCategoryRelMapper.updateRelByVideoId(reqVO.getId(), reqVO.getCategoryId());

        // 修改视频课程_标签关联
        videoTagRelMapper.updateRelByVideoId(reqVO.getId(), reqVO.getTagId());
        return ResponseData.success();
    }

    @Override
    public ResponseData selectById(IdTypeReqVO reqVO) {
        if(reqVO.getType() == 0) {
            ArticleCourseDO articleCourseDO = articleCourseMapper.selectById(reqVO.getId());
            FindCourseDetailsRspVO courseDetailsRspVO = new FindCourseDetailsRspVO();
            BeanUtils.copyProperties(articleCourseDO, courseDetailsRspVO);
            courseDetailsRspVO.setContentOrLocation(articleCourseDO.getContent());
            courseDetailsRspVO.setUsername(userMapper.selectById(articleCourseDO.getUserId()).getUsername());
            LambdaQueryWrapper<ArticleCategoryRelDO> wrapperCategory = Wrappers.lambdaQuery();
            wrapperCategory.eq(ArticleCategoryRelDO::getArticleId, reqVO.getId());
            LambdaQueryWrapper<ArticleTagRelDO> wrapperTag = Wrappers.lambdaQuery();
            wrapperTag.eq(ArticleTagRelDO::getArticleId, reqVO.getId());
            courseDetailsRspVO.setCategoryId(articleCategoryRelMapper.selectOne(wrapperCategory).getCategoryId());
            courseDetailsRspVO.setTagId(articleTagRelMapper.selectOne(wrapperTag).getTagId());
            return ResponseData.success(courseDetailsRspVO);
        }else {
            VideoCourseDO videoCourseDO = videoCourseMapper.selectById(reqVO.getId());
            FindCourseDetailsRspVO courseDetailsRspVO = new FindCourseDetailsRspVO();
            BeanUtils.copyProperties(videoCourseDO, courseDetailsRspVO);
            courseDetailsRspVO.setContentOrLocation(videoCourseDO.getLocation());
            courseDetailsRspVO.setUsername(userMapper.selectById(videoCourseDO.getUserId()).getUsername());
            LambdaQueryWrapper<VideoCategoryRelDO> wrapperCategory = Wrappers.lambdaQuery();
            wrapperCategory.eq(VideoCategoryRelDO::getVideoId, reqVO.getId());
            LambdaQueryWrapper<VideoTagRelDO> wrapperTag = Wrappers.lambdaQuery();
            wrapperTag.eq(VideoTagRelDO::getVideoId, reqVO.getId());
            courseDetailsRspVO.setCategoryId(videoCategoryRelMapper.selectOne(wrapperCategory).getCategoryId());
            courseDetailsRspVO.setTagId(videoTagRelMapper.selectOne(wrapperTag).getTagId());
            return ResponseData.success(courseDetailsRspVO);
        }
    }

}
